import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../services/storage_service.dart';
import '../services/api_service.dart';
import '../types/app_types.dart';

part 'app_providers.g.dart';

// ========== 服务提供者 ==========

/**
 * 存储服务提供者
 */
@riverpod
StorageService storageService(StorageServiceRef ref) {
  return StorageService();
}

/**
 * API 客户端提供者
 */
@riverpod
ApiClient apiClient(ApiClientRef ref) {
  return ApiClient();
}

// ========== 数据提供者 ==========

/**
 * 文件夹列表提供者
 */
@riverpod
Future<List<Folder>> folders(FoldersRef ref) async {
  final storage = ref.watch(storageServiceProvider);
  return await storage.getFolders();
}

/**
 * 笔记列表提供者
 */
@riverpod
Future<List<Note>> notes(NotesRef ref) async {
  final storage = ref.watch(storageServiceProvider);
  return await storage.getNotes();
}

/**
 * 根据文件夹ID获取笔记
 */
@riverpod
Future<List<Note>> notesByFolder(NotesByFolderRef ref, int folderId) async {
  final storage = ref.watch(storageServiceProvider);
  if (folderId == 1) {
    // 全部笔记
    return await storage.getNotes();
  }
  return await storage.getNotesByFolderId(folderId);
}

/**
 * 当前选中的文件夹
 */
@riverpod
class CurrentFolder extends _$CurrentFolder {
  @override
  int build() => 1; // 默认选中"全部笔记"

  void setFolder(int folderId) {
    state = folderId;
  }
}

/**
 * 当前选中的笔记
 */
@riverpod
class CurrentNote extends _$CurrentNote {
  @override
  Note? build() => null;

  void setNote(Note? note) {
    state = note;
  }

  void clearNote() {
    state = null;
  }
}

/**
 * 搜索查询
 */
@riverpod
class SearchQuery extends _$SearchQuery {
  @override
  String build() => '';

  void setQuery(String query) {
    state = query;
  }

  void clearQuery() {
    state = '';
  }
}

/**
 * 搜索结果
 */
@riverpod
Future<List<Note>> searchResults(SearchResultsRef ref) async {
  final query = ref.watch(searchQueryProvider);
  if (query.isEmpty) return [];
  
  final storage = ref.watch(storageServiceProvider);
  return await storage.searchNotes(query);
}

/**
 * 文件夹笔记数量统计
 */
@riverpod
Future<Map<int, int>> folderNoteCounts(FolderNoteCountsRef ref) async {
  final storage = ref.watch(storageServiceProvider);
  final notes = await storage.getNotes();
  final folders = await storage.getFolders();
  
  final counts = <int, int>{};
  
  // 统计每个文件夹的笔记数量
  for (final folder in folders) {
    if (folder.id == 1) {
      // 全部笔记
      counts[folder.id] = notes.length;
    } else {
      counts[folder.id] = notes.where((note) => note.folderId == folder.id).length;
    }
  }
  
  return counts;
}

// ========== 应用状态提供者 ==========

/**
 * 设置面板显示状态
 */
@riverpod
class ShowSettings extends _$ShowSettings {
  @override
  bool build() => false;

  void toggle() {
    state = !state;
  }

  void show() {
    state = true;
  }

  void hide() {
    state = false;
  }
}

/**
 * 同步状态提供者
 */
@riverpod
class SyncStatusNotifier extends _$SyncStatusNotifier {
  @override
  SyncStatusInfo build() {
    return const SyncStatusInfo(
      status: SyncStatus.idle,
      message: '未同步',
      lastSyncTime: null,
      progress: 0.0,
    );
  }

  void updateStatus(SyncStatusInfo statusInfo) {
    state = statusInfo;
  }

  void startSync() {
    state = state.copyWith(
      status: SyncStatus.syncing,
      message: '正在同步...',
      progress: 0.0,
    );
  }

  void updateProgress(double progress, String message) {
    state = state.copyWith(
      progress: progress,
      message: message,
    );
  }

  void completeSync({String? message}) {
    state = state.copyWith(
      status: SyncStatus.synced,
      message: message ?? '同步完成',
      lastSyncTime: DateTime.now(),
      progress: 1.0,
    );
  }

  void failSync(String errorMessage) {
    state = state.copyWith(
      status: SyncStatus.error,
      message: errorMessage,
      progress: 0.0,
    );
  }
}

/**
 * 通知管理器
 */
@riverpod
class NotificationNotifier extends _$NotificationNotifier {
  @override
  List<AppNotification> build() => [];

  /**
   * 添加通知
   */
  void addNotification(AppNotification notification) {
    state = [...state, notification];
  }

  /**
   * 移除通知
   */
  void removeNotification(String id) {
    state = state.where((notification) => notification.id != id).toList();
  }

  /**
   * 清空所有通知
   */
  void clearNotifications() {
    state = [];
  }

  /**
   * 显示成功通知
   */
  void showSuccess({
    String? title,
    required String message,
    Duration? duration,
  }) {
    addNotification(AppNotification.success(
      title: title,
      message: message,
      duration: duration,
    ));
  }

  /**
   * 显示错误通知
   */
  void showError({
    String? title,
    required String message,
    Duration? duration,
  }) {
    addNotification(AppNotification.error(
      title: title,
      message: message,
      duration: duration,
    ));
  }

  /**
   * 显示警告通知
   */
  void showWarning({
    String? title,
    required String message,
    Duration? duration,
  }) {
    addNotification(AppNotification.warning(
      title: title,
      message: message,
      duration: duration,
    ));
  }

  /**
   * 显示信息通知
   */
  void showInfo({
    String? title,
    required String message,
    Duration? duration,
  }) {
    addNotification(AppNotification.info(
      title: title,
      message: message,
      duration: duration,
    ));
  }
}

// ========== 数据操作提供者 ==========

/**
 * 应用数据管理器
 */
@riverpod
class AppDataNotifier extends _$AppDataNotifier {
  @override
  AppData build() {
    return const AppData(
      folders: [],
      notes: [],
      currentFolderId: 1,
      currentNote: null,
      searchQuery: '',
      showSettings: false,
    );
  }

  /**
   * 加载应用数据
   */
  Future<void> loadData() async {
    final storage = ref.read(storageServiceProvider);
    final folders = await storage.getFolders();
    final notes = await storage.getNotes();
    
    state = state.copyWith(
      folders: folders,
      notes: notes,
    );
  }

  /**
   * 创建文件夹
   */
  Future<Folder> createFolder(String name) async {
    final storage = ref.read(storageServiceProvider);
    final folder = Folder(
      id: 0, // 将由数据库自动分配
      name: name,
      count: 0,
      isDefault: false,
      isShared: false,
      sortOrder: 0,
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
      syncStatus: SyncStatus.local,
    );
    
    final createdFolder = await storage.createFolder(folder);
    
    // 刷新文件夹列表
    ref.invalidate(foldersProvider);
    
    return createdFolder;
  }

  /**
   * 更新文件夹
   */
  Future<Folder> updateFolder(Folder folder) async {
    final storage = ref.read(storageServiceProvider);
    final updatedFolder = await storage.updateFolder(folder);
    
    // 刷新文件夹列表
    ref.invalidate(foldersProvider);
    
    return updatedFolder;
  }

  /**
   * 删除文件夹
   */
  Future<void> deleteFolder(int folderId) async {
    final storage = ref.read(storageServiceProvider);
    await storage.deleteFolder(folderId);
    
    // 刷新相关数据
    ref.invalidate(foldersProvider);
    ref.invalidate(notesProvider);
    ref.invalidate(folderNoteCountsProvider);
  }

  /**
   * 创建笔记
   */
  Future<Note> createNote({
    required String title,
    required String content,
    int? folderId,
  }) async {
    final storage = ref.read(storageServiceProvider);
    final note = Note(
      id: 0, // 将由数据库自动分配
      title: title,
      content: content,
      folderId: folderId ?? 2, // 默认为"未分类"
      createdAt: DateTime.now(),
      updatedAt: DateTime.now(),
      syncStatus: SyncStatus.local,
      tags: [],
      isShared: false,
    );
    
    final createdNote = await storage.createNote(note);
    
    // 刷新相关数据
    ref.invalidate(notesProvider);
    ref.invalidate(folderNoteCountsProvider);
    
    return createdNote;
  }

  /**
   * 更新笔记
   */
  Future<Note> updateNote(Note note) async {
    final storage = ref.read(storageServiceProvider);
    final updatedNote = await storage.updateNote(note);
    
    // 刷新相关数据
    ref.invalidate(notesProvider);
    
    return updatedNote;
  }

  /**
   * 删除笔记
   */
  Future<void> deleteNote(int noteId) async {
    final storage = ref.read(storageServiceProvider);
    await storage.deleteNote(noteId);
    
    // 刷新相关数据
    ref.invalidate(notesProvider);
    ref.invalidate(folderNoteCountsProvider);
  }

  /**
   * 移动笔记到指定文件夹
   */
  Future<Note> moveNoteToFolder(Note note, int targetFolderId) async {
    final updatedNote = note.copyWith(
      folderId: targetFolderId,
      updatedAt: DateTime.now(),
      syncStatus: SyncStatus.modified,
    );
    
    return await updateNote(updatedNote);
  }
}